<?php

namespace api\sms\driver;

class Zhutong extends Sms
{

    // 错误码
    private array $errorCode = [
        '4000' => '余额不足',
        '4001' => '用户名错误',
        '4002' => '密码不能为空',
        '4004' => '手机号码错误',
        '4006' => 'IP鉴权错误',
        '4007' => '用户禁用',
        '4008' => 'tKey错误',
        '4009' => '密码错误',
        '4013' => '定时时间错误',
        '4014' => '模板错误',
        '4015' => '扩展号错误',
        '4019' => '用户类型错误',
        '4023' => '签名错误',
        '4025' => '模板变量内容为空',
        '4026' => '手机号码数最大2000个',
        '4027' => '模板变量内容最大200组',
        '4029' => '请使用post请求',
        '4030' => 'Content-Type请使用application/json',
        '4062' => '账号未认证',
        '9998' => 'JSON解析错误',
        '9999' => '非法请求'
    ];

    /**
     * 发送短信
     *
     * @param string $phone 手机号
     * @param array $data 发送数据
     * @return bool
     */
    public function sendSms(string $phone, array $data): bool
    {
        try {
            $time = time();
            $this->setContent($data['content']);
            $requestParams = [
                'username' => $this->config['zhutong_username'] ?? '',
                'password' => md5(md5($this->config['zhutong_password'] ?? '') . $time),
                'signature' => $this->config['signature'] ?? '',
                'tpId' => $data['template_id'],
                'tKey' => $time,
                'records' => [
                    [
                        'mobile' => $phone,
                        'tpContent' => $data['params']
                    ]
                ]
            ];

            $client = new \GuzzleHttp\Client();
            $response = $client->request('POST', 'https://api.mix2.zthysms.com/v2/sendSmsTp', [
                'verify' => app()->getRootPath() . 'cacert.pem',
                'json' => $requestParams
            ]);
            $params = json_decode($response->getBody(), true);
            $this->setSendStatus($params['code'] === 200);
            if ($params['code'] !== 200) {
                $this->setErrorMessage($this->errorCode[$params['code']] ?? '');
            }
        } catch (\Throwable $e) {
            $this->setSendStatus(false);
            $this->setErrorMessage('系统错误 ' . $e->getMessage());
        }

        return $this->getSendStatus();
    }
}